import 'package:blurb/common/routers/pages.dart';
import 'package:blurb/common/store/store_provider.dart';
import 'package:blurb/common/store/topic_store.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:blurb/common/store/share_store.dart';
import 'package:blurb/common/store/comment_store.dart';
import 'package:blurb/common/services/user_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:blurb/pages/community/sharing_publish.dart';

void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 清除SharedPreferences的缓存数据
  await _clearSharedPreferencesCache();
  
  // 清除当前登录用户信息，但保留用户数据库
  await UserService.logout();
  
  // 初始化Store
  final storeProvider = StoreProvider();
  await storeProvider.init();
  
  runApp(
    // 使用MultiProvider提供多个Store实例
    MultiProvider(
      providers: [
    Provider<UserStore>.value(
      value: storeProvider.userStore,
        ),
        Provider<ShareStore>.value(
          value: storeProvider.shareStore,
        ),
        Provider<CommentStore>.value(
          value: storeProvider.commentStore,
        ),
        Provider<TopicStore>.value(
          value: storeProvider.topicStore,
        ),
      ],
      child: const MyApp(),
    ),
  );
}

// 清除SharedPreferences的缓存数据
Future<void> _clearSharedPreferencesCache() async {
  try {
    final prefs = await SharedPreferences.getInstance();
    
    // 获取所有键
    final keys = prefs.getKeys();
    
    // 保留一些必要的键（如果有需要）
    final keysToKeep = <String>[];
    
    // 删除不需要保留的键
    for (final key in keys) {
      if (!keysToKeep.contains(key)) {
        await prefs.remove(key);
      }
    }
    
    // 清除SharingPublishPage中的图片缓存
    SharingPublishPage.publishedImages.clear();
    
    debugPrint('已清除SharedPreferences缓存数据');
  } catch (e) {
    debugPrint('清除SharedPreferences缓存数据失败: $e');
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(414, 896),
      builder: (context, child) {
        return MaterialApp.router(
          title: 'Blurb',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF60C3FF)),
            useMaterial3: true,
          ),
          debugShowCheckedModeBanner: false,
          routerConfig: RPS.routers,
          builder: (context, widget) {
            // 使用 FToast 进行初始化
            final FToast fToast = FToast();
            fToast.init(context);
            return MediaQuery(
              data: MediaQuery.of(
                context,
              ).copyWith(textScaler: const TextScaler.linear(1.0)),
              child: widget!,
            );
          },
        );
      },
    );
  }
}